<template>
  <el-card class="pb-3 w-full">
    <el-row class="overflow-auto" :gutter="24">
      <!--  语言 - 类型 - 系列  -->
      <el-col :sm="12" :md="8" :lg="6">
        <span>语言</span>
        <el-select
          :disabled="route.query.operate === 'edit'"
          v-model.trim="productInfo.Language"
          class="w-full"
          placeholder="请选择语言"
          @change="productInfo.Type = ''"
        >
          <el-option
            v-for="item in languageOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-col>
      <el-col :sm="12" :md="8" :lg="6">
        <span>类型</span>
        <el-select
          :disabled="route.query.operate === 'edit'"
          placeholder="请选择商品类型"
          v-model.trim="productInfo.Type"
          class="w-full"
        >
          <el-option
            v-for="item of returnProductTypeOptions(productInfo.Language)"
            :key="item.label"
            :disabled="returnProductTypeOptions(productInfo.Language)?.length == 1"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-col>
      <el-col :sm="12" :md="8" :lg="6">
        <span>系列</span>
        <el-select
          :disabled="route.query.operate === 'edit'"
          placeholder="请选择商品系列"
          v-model.trim="productInfo.Series"
          class="w-full"
        >
          <el-option
            v-for="item of returnProductSeriesOptions(productInfo.Language, productInfo.Type)"
            :key="item.label"
            :disabled="
              returnProductSeriesOptions(productInfo.Language, productInfo.Type)?.length == 1
            "
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-col>
      <!--   商品名字 - 商品介绍  -->
      <el-col :sm="12" :md="8" :lg="6">
        <span>商品名字</span>
        <el-input v-model.trim="productInfo.Name" placeholder="请输入商品名称"></el-input>
      </el-col>
      <el-col :sm="12" :md="8" :lg="6">
        <span>商品介绍</span>
        <el-input
          v-model.trim="productInfo.Desc"
          show-word-limit
          maxlength="1024"
          type="textarea"
        ></el-input>
      </el-col>
      <!-- 文件显示选择 -->

      <el-col
        class="mb-2 overflow-hidden"
        v-for="item of baseData"
        :key="item.attribute"
        :sm="12"
        :md="8"
        :lg="6"
      >
        <span>{{ item.name }}</span>
        <select-file
          :show-mode="item.showMode"
          v-model="productInfo[item.attribute as keyof typeof productInfo]"
        ></select-file>
      </el-col>

      <!-- 页面跳转设置按钮 -->
      <el-col :sm="12" :md="8" :lg="6">
        <ul>
          <li class="flex items-center gap-3">
            <span>中文页面</span>
            <el-button @click="HandlePreviewPage('zh')">设置</el-button>
            <el-button @click="HandleOpenZhView('zh')">预览</el-button>
          </li>
          <li class="flex my-1 items-center gap-3">
            <span>英文页面</span>
            <el-button @click="HandlePreviewPage('en')">设置</el-button>
            <el-button @click="HandleOpenZhView('en')">预览</el-button>
          </li>
          <li class="flex items-center gap-3">
            <span>俄文页面</span>
            <el-button @click="HandlePreviewPage('ru')">设置</el-button>
            <el-button @click="HandleOpenZhView('ru')">预览</el-button>
          </li>
        </ul>
      </el-col>
      <!--  -->
      <template v-if="productInfo.Type && productInfo.Series">
        <template v-for="item of productAttribute" :key="item">
          <el-col :sm="12" :md="8" :lg="6">
            <span>{{ productAttributeOBJ[item] }}</span>
            <el-input
              type="textarea"
              v-model.trim="productInfo[item as keyof typeof productInfo]"
              :placeholder="`请输入${productAttributeOBJ[item]}`"
            />
          </el-col>
        </template>
      </template>
    </el-row>
    <!--    -->
    <div class="flex fixed bottom-0 bg-white">
      <el-button
        v-if="route.query.type"
        :disabled="route.query.operate === 'copy'"
        @click="HandlerUpdateClick"
        class="w-20"
        type="success"
        >更新</el-button
      >
      <el-button
        :disabled="route.query.operate === 'edit'"
        @click="HandlerAddProductClick"
        class="w-20"
        type="primary"
        >添加</el-button
      >
    </div>
    <el-dialog v-model="dialogVisible" :title="`${setPreview}`" width="1000">
      <div>
        <el-select class="w-1/4" placeholder="请选择语言" v-model.trim="previewData.Language">
          <el-option
            v-for="item in languageOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select placeholder="请选择商品类型" class="w-1/4" v-model.trim="previewData.Type">
          <el-option
            v-for="item of returnProductTypeOptions(previewData.Language)"
            :key="item.label"
            :disabled="returnProductTypeOptions(previewData.Language)?.length == 1"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-select placeholder="请选择商品系列" class="w-1/4" v-model.trim="previewData.Series">
          <el-option
            v-for="item of returnProductSeriesOptions(previewData.Language, previewData.Type)"
            :key="item.label"
            :disabled="
              returnProductSeriesOptions(previewData.Language, previewData.Type)?.length == 1
            "
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-input
          v-model.trim="previewData.Name"
          @keydown="HandlerSearchPreviewClick($event)"
          placeholder="请输入商品的名字 （回车搜索）"
          class="w-1/4"
        ></el-input>
      </div>
      <div>
        <div class="flex my-1 border justify-between text-center items-center">
          <span class="flex-1 py-2">语言</span>
          <span class="flex-1 py-2">类型</span>
          <span class="flex-1 py-2">系列</span>
          <span class="flex-1 py-2">名称</span>
          <span class="flex-1 py-2">操作</span>
        </div>
        <ul class="max-h-72 overflow-auto">
          <template v-if="!preViewArray.length">
            <li class="text-center py-3">当前条件没有数据~</li>
          </template>
          <template v-for="(item, index) of preViewArray" :key="index">
            <li
              @click="currentPreView = item"
              class="flex cursor-pointer text-center my-1 border justify-between items-center"
              :class="{ 'border-blue-400': currentPreView.ID == item.ID }"
            >
              <div class="flex-1">{{ item.Language }}</div>
              <div class="flex-1">{{ item.Type }}</div>
              <div class="flex-1">{{ item.Series }}</div>
              <div class="flex-1">{{ item.Name }}</div>
              <a
                class="py-2 px-3 flex-1"
                target="_blank"
                :href="`http://dongsongkeji.com.cn/${item.Language}/product-detail/${item.Language}/${item.Type}/${item.Series}/${item.Name}`"
              >
                预览
              </a>
            </li>
          </template>
        </ul>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="HandleReturnPreview"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { languageOptions, useDebounce, returnProductTypeOptions } from '@/utils'
import { computed, onBeforeUnmount, onMounted, onUnmounted, reactive, ref, shallowRef } from 'vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import SelectFile from '@/components/select-file/select-file.vue'
import { ReturnSericesConfig } from './config'
import { FindProductService, GenerateProductService, UpdateProductService } from '@/service/product'
import router from '@/router'
const editorRef = shallowRef()
const route = useRoute()
const productInfo = ref<any>({})
const dialogVisible = ref(false)
// 预览的页面
const setPreview = ref('')
// 选中的值
const currentPreView = ref<any>({})
const preViewArray = ref<any[]>([])
// 动态对象
const productAttributeOBJ = computed(() => {
  return ReturnSericesConfig(productInfo.value.Type, productInfo.value.Series)
})

const baseData = [
  {
    name: '商品轮播图',
    attribute: 'Cover',
    showMode: "image"
  },
  {
    name: '商品文档',
    attribute: 'Document',
    showMode: "file"
  },
  {
    name: '商品模型',
    attribute: 'Model3D',
    showMode: "file"
  },
  {
    name: '商品尺寸图',
    attribute: 'DimensionDrawing',
    showMode: "drawing"
  },
  {
    name: '商品接线图',
    attribute: 'ConnectLine',
    showMode: "drawing"
  }
]

// 动态属性数组
const productAttribute = computed(() => {
  const value = ReturnSericesConfig(productInfo.value.Type, productInfo.value.Series)
  return Object.keys(value) ?? []
})
// 预览数据
const previewData = reactive({
  Language: '',
  Type: '',
  Series: '',
  Name: ''
})
// 打开页面
function HandlePreviewPage(target: string) {
  dialogVisible.value = true
  setPreview.value = target
}

// 回车搜索
const de = useDebounce(() => {
  FindProductService(previewData).then((res) => {
    preViewArray.value = res.data
  })
})
function HandlerSearchPreviewClick(event: KeyboardEvent) {
  if (event.code === 'Enter') {
    if (!previewData.Language || !previewData.Type || !previewData.Series || !previewData.Name) {
      ElMessage({
        type: 'warning',
        message: '请完善信息再搜索'
      })
      return
    }
    de()
  }
}
// 预览
function HandleOpenZhView(target: string) {
  if (!productInfo.value[target]) {
    ElMessage({
      type: 'warning',
      message: '该预览的页面还没设置，请先设置再进行预览'
    })
    return
  }
  window.open(productInfo.value[target])
}
function HandleReturnPreview() {
  const { Language, Type, Series, Name } = currentPreView.value
  productInfo.value[setPreview.value] =
    `/${Language}/product-detail/${Language}/${Type}/${Series}/${Name}`
  dialogVisible.value = false
}

onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

async function HandlerAddProductClick() {
  const item = productInfo.value
  if (!item.Language || !item.Type || !item.Series || !item.Name) {
    ElMessage({
      type: 'error',
      message: '信息不完整,请继续填写!'
    })
    return
  }
  const { Language, Type, Series, Name } = item
  switch (item.Language) {
    case 'zh':
      item.zh = `/zh/product-detail/${Language}/${Type}/${Series}/${Name}`
      break
    case 'en':
      item.en = `/en/product-detail/${Language}/${Type}/${Series}/${Name}`
      break
    case 'ru':
      item.ru = `/ru/product-detail/${Language}/${Type}/${Series}/${Name}`
      break
  }
  const res = await GenerateProductService(item)
  if (res.code == 1) return
  await router.push(
    `/home/product?type=${productInfo.value.Type}&lng=${productInfo.value.Language}`
  )
}
async function HandlerUpdateClick() {
  const res = await UpdateProductService(productInfo.value)
  ElMessage({
    type: res.code === 0 ? 'success' : 'error',
    message: res.msg
  })
  if (res.code == 1) return
  await router.push(
    `/home/product?type=${productInfo.value.Type}&lng=${productInfo.value.Language}`
  )
}
function handlePated(event: any) {
  // 获取剪贴板数据
  var clipboardData = event.clipboardData
  var pastedData = clipboardData.getData('Text')?.split('\n') ?? []
  if (pastedData.length > 5) {
    event.preventDefault()
    const cus: any = {}
    // 遍历现成的对象 => 和粘贴值做比较 => 比较完成之后赋值 productInfo
    pastedData.forEach((item: string) => {
      Object.keys(productAttributeOBJ.value)?.forEach((itemKey) => {
        const arr = item.split('\t')
        if (productAttributeOBJ.value[itemKey] == arr[0]?.trim()) {
          cus[itemKey] = arr[1]?.trim()
        }
      })
    })
    productInfo.value = { ...productInfo.value, ...cus }
  }
}
onMounted(async () => {
  try {
    document.addEventListener('paste', handlePated)
    if (route.query.id) {
      if (route.query.operate === 'edit') {
        const res = await FindProductService({
          Type: route.query.type,
          id: route.query.id
        })
        productInfo.value = res.data[0]
      } else {
        const res = await FindProductService({
          Type: route.query.type,
          id: route.query.id
        })
        delete res.data[0].ID
        delete res.data[0].CreatedAt
        delete res.data[0].UpdatedAt
        productInfo.value = res.data[0]
      }
    }
  } catch (error) {
    console.log('first mounted try => ', error)
  }
})
onUnmounted(() => {
  document.removeEventListener('paste', handlePated)
})
// 根据语言 返回商品的类型 中文 英文 俄文

function returnProductSeriesOptions(Language: string, Type: string) {
  if (!Type) {
    return [
      {
        label: '请先选择类型',
        value: '请先选择类型'
      }
    ]
  }
  switch (Language) {
    case 'zh':
      switch (Type) {
        case '电感式传感器':
          return [
            {
              label: '标准功能系列',
              value: '标准功能系列'
            },
            {
              label: '本质安全系列',
              value: '本质安全系列'
            },
            {
              label: '模拟量输出系列',
              value: '模拟量输出系列'
            }
          ]
        case '电容式传感器':
          return [
            {
              label: '标准功能系列',
              value: '标准功能系列'
            },
            {
              label: '频率增强系列',
              value: '频率增强系列'
            },
            {
              label: '增强远距离系列',
              value: '增强远距离系列'
            }
          ]
        case '光电式传感器':
          return [
            {
              label: '微扁形系列(PSV)',
              value: '微扁形系列(PSV)'
            },
            {
              label: '微方形系列(PST/PSJ)',
              value: '微方形系列(PST/PSJ)'
            },
            {
              label: '小方形系列(PSE)',
              value: '小方形系列(PSE)'
            }
          ]
        case '测量传感器':
          return [
            {
              label: '高精度激光位移传感器',
              value: '高精度激光位移传感器'
            },
            {
              label: '激光位移传感器',
              value: '激光位移传感器'
            }
          ]
        default:
          return []
      }
    case 'en':
      switch (Type) {
        case 'InductiveSensor':
          return [
            {
              label: 'StandardFunctionSeries',
              value: 'StandardFunctionSeries'
            },
            {
              label: 'IntrinsicSafetySeries',
              value: 'IntrinsicSafetySeries'
            },
            {
              label: 'AnalogOutputSeries',
              value: 'AnalogOutputSeries'
            }
          ]
        case 'CapacitiveSensor':
          return [
            {
              label: 'StandardFunctionSeries',
              value: 'StandardFunctionSeries'
            },
            {
              label: 'FrequencyEnhancedSeries',
              value: 'FrequencyEnhancedSeries'
            },
            {
              label: 'EnhancedLongRangeSeries',
              value: 'EnhancedLongRangeSeries'
            }
          ]
        case 'PhotoelectricSensor':
          return [
            {
              label: 'MicroFlatSeries(PSV)',
              value: 'MicroFlatSeries(PSV)'
            },
            {
              label: 'MicroSquareSeries(PST/PSJ)',
              value: 'MicroSquareSeries(PST/PSJ)'
            },
            {
              label: 'SmallSquareSeries(PSE)',
              value: 'SmallSquareSeries(PSE)'
            }
          ]
        case 'MeasurementSensor':
          return [
            {
              label: 'High-precision laser displacement sensor',
              value: 'High-precision laser displacement sensor'
            },
            {
              label: 'Laser displacement sensor',
              value: 'Laser displacement sensor'
            }
          ]
        default:
          return []
      }
    case 'ru':
      switch (Type) {
        case 'Индуктивныйдатчик':
          return [
            {
              label: 'Стандартнаяфункциональнаясерия',
              value: 'Стандартнаяфункциональнаясерия'
            },
            {
              label: 'Серияпоинтринсическойбезопасности',
              value: 'Серияпоинтринсическойбезопасности'
            },
            {
              label: 'Серияаналогическоговыхода',
              value: 'Серияаналогическоговыхода'
            }
          ]
        case 'Конденсаторныйдатчик':
          return [
            {
              label: 'Стандартнаяфункциональнаясерия',
              value: 'Стандартнаяфункциональнаясерия'
            },
            {
              label: 'Серияповышеннойчастоты',
              value: 'Серияповышеннойчастоты'
            },
            {
              label: 'Серияповышеннойдальности',
              value: 'Серияповышеннойдальности'
            }
          ]
        case 'Фотоэлектрическийдатчик':
          return [
            {
              label: 'Микроплоскостнаясерия(PSV)',
              value: 'Микроплоскостнаясерия(PSV)'
            },
            {
              label: 'Микроквадратнаясерия(PST/PSJ)',
              value: 'Микроквадратнаясерия(PST/PSJ)'
            },
            {
              label: 'Малоквадратнаясерия(PSE)',
              value: 'Малоквадратнаясерия(PSE)'
            }
          ]
        case 'Измерительныйдатчик':
          return [
            {
              label: 'Высокоточный лазерный датчик перемещения',
              value: 'Высокоточный лазерный датчик перемещения'
            },
            {
              label: 'лазерный датчик смещения',
              value: 'лазерный датчик смещения'
            }
          ]
        default:
          return []
      }
  }
}
</script>

<style>
.el-row > .el-col {
  margin-bottom: 10px;
}
.el-col span {
  font-weight: 700;
}
</style>
